import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Button, Modal, Divider, InputNumber, Checkbox, Tag,Radio } from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '../search.less';
import { ruleP, nameMinLength, nameMaxLength, remarkMaxLength } from '@/utils/rule';

const { TextArea } = Input;
const FormItem = Form.Item;
const formLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 18 },
};
const viewLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
const CreateForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    addDataFn,
    updateFn,
    handleModalVisible,
    text,
    form: { getFieldValue },
    loadingupdate,
    loadingadd,  
  } = props;
  const sceneMinLength = (rule, val, callback) => {
    if (!val) {
      callback();
    }
    if (val > getFieldValue('maxLength') || (val > getFieldValue('maxLength') && val > 9999)) {
      callback('应小于最大长度');
    }
    if (val < getFieldValue('maxLength') && (val < 1 || val > 9999)) {
      callback('长度范围为1-9999');
    }
    callback();
  };

  const sceneMaxLength = (rule, val, callback) => {
    if (!val) {
      callback();
    }
    if (val < getFieldValue('minLength') || (val < getFieldValue('minLength') && val < 0)) {
      callback('应大于最小长度');
    }
    if (val > getFieldValue('minLength') && (val < 1 || val > 9999)) {
      callback('长度范围为1-9999');
    }

    callback();
  };

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (text) {        
        updateFn(fieldsValue, text);        
      } else {
        addDataFn(fieldsValue);
      }
    });
  };
  

  return (
    <Modal
      destroyOnClose
      width={640}
      title={text ? '编辑场景' : '新增场景'}
      visible={modalVisible}
      onOk={okHandle}
      confirmLoading={loadingupdate || loadingadd}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <Row gutter={16}>
      <Col md={24}>
          <FormItem {...formLayout} label="场景编码">
            {form.getFieldDecorator('sceneCode', {
              rules: [
                { required: true, whitespace:true, message: '场景编码不能为空' },                
              ],
              initialValue: (text && text.sceneCode) || '',
            })(<Input placeholder="请输入" />)}
          </FormItem>
        </Col>

        <Col md={24}>
          <FormItem {...formLayout} label="场景名称">
            {form.getFieldDecorator('sceneName', {
              rules: [
                { required: true, message: '场景名称不能为空' },
                { pattern: new RegExp(ruleP(11)[0], 'g'), message: ruleP(11)[1] },
                { min: nameMinLength()[0], message: nameMinLength()[1] },
                { max: nameMaxLength()[0], message: nameMaxLength()[1] },
              ],
              initialValue: (text && text.sceneName) || '',
            })(<Input placeholder="请输入" />)}
          </FormItem>
        </Col>

        <Col md={24}>
          <Form layout="inline">
            <FormItem labelCol={{ span: 13 }} wrapperCol={{ span: 11 }} label="敏感数据长度">
              {form.getFieldDecorator('minLength', {
                rules: [
                  { required: true, message: '长度不能为空' },
                  { validator: sceneMinLength },                 
                ],
                initialValue: (text && text.minLength) || 10,
              })(<InputNumber min={0} max={99999} style={{ width: 120 }} />)}
            </FormItem>
            <FormItem style={{ width: '20px', textAlign: 'right' }}>-</FormItem>
            <FormItem>
              {form.getFieldDecorator('maxLength', {
                rules: [
                  { required: true, message: '长度不能为空' },
                  { validator: sceneMaxLength },                 
                ],
                initialValue: (text && text.maxLength) || 20,
              })(<InputNumber min={1} max={99999} style={{ width: 120 }} />)}
            </FormItem>
          </Form>
      </Col>      

      <Col md={24} style={{marginTop:8}}>
          <FormItem {...formLayout} label="正则表达式">
            {form.getFieldDecorator('regularExpression', {
              rules: [ { required: true, whitespace:true, message: '正则表达式不能为空' },],
              initialValue: text && text.regularExpression ||'',
            })(<TextArea  autoSize={{ minRows: 3, maxRows: 5 }} placeholder="请输入" />)}
          </FormItem>
        </Col>

        <Col md={24}>
          <FormItem {...formLayout} label="模糊搜索">
          {form.getFieldDecorator('ifSearch', {initialValue: text? text.ifSearch:1
          })(
          <Radio.Group>
             <Radio value={1}>支持</Radio> 
            <Radio value={0}>不支持</Radio>                     
          </Radio.Group>
            )}
          </FormItem>
        </Col> 
        
        {getFieldValue('ifSearch') == 0 ?(
        <Col md={24}>
        <FormItem {...formLayout} label="更新密钥">
        {form.getFieldDecorator('ifUpdateKey', {initialValue: text ? text.ifUpdateKey:1
        })(
        <Radio.Group>
          <Radio value={1}>支持</Radio>      
          <Radio value={0}>不支持</Radio>               
        </Radio.Group>
          )}
        </FormItem>
        </Col>
        ):null}   

        <Col md={24}>
          <FormItem {...formLayout} label="备注">
            {form.getFieldDecorator('remark', {
              rules: [{ max: remarkMaxLength()[0], message: remarkMaxLength()[1] }],
              initialValue: text && text.remark || '',
            })(<TextArea style={{ minHeight: 32 }} rows={2} placeholder="请输入" />)}
          </FormItem>
        </Col>
      </Row>
    </Modal>
  );
});
@Form.create()
/* eslint react/no-multi-comp:0 */
@connect(
  ({ scene, loading }) => ({
    scene,
    loading: loading.models.scene,
    loadingadd: loading.effects['scene/add'],
    loadingupdate: loading.effects['scene/update'],
  }),
  dispatch => ({
    queryList: e => dispatch({ type: 'scene/queryList', payload: e }),  
    dispatch,
  })
)
class scene extends PureComponent {
  state = {
    modalVisible: false,    
    selectedRows: [],
    formValues: {},
    text: {}, 
  };

  columns = [
    {
      title: '场景编码',
      dataIndex: 'sceneCode',
      key: 'sceneCode',
    },
    {
      title: '场景名称',
      dataIndex: 'sceneName',
      key: 'sceneName',
    },
    {
      title: '敏感数据长度',
      render: text => (
        <Fragment>
        {text.minLength} ~ {text.maxLength}
        </Fragment>),
     },      
    {
      title: '是否内置',
      dataIndex: 'ifBuiltin',  
      render: text => (
        <Fragment>
        {text == 1?(<Tag color="green">是</Tag>):(<Tag color="red">否</Tag>)}
        </Fragment>),         
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis:true,      
    },
    
    {
      title: '操作',
      width:160,
      render: (text) => (
        <Fragment> 
           <a onClick={() => this.handleView(true, text)}>详情</a>          
          <Divider type="vertical" />        
          <a onClick={() => this.handleModalVisible(true, text)}>编辑</a>          
          {text.ifBuiltin == 1?null:(
            <Fragment>
             <Divider type="vertical" />
             <a onClick={() => this.deleteData(text.sceneId)}>删除</a>  
             </Fragment>
          )}         
        </Fragment>
      ),
    },
  ];

  deleteData = id => {
    Modal.confirm({
      title: '删除',
      content: '您确认要删除选择的数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleThisRowDelete(id),
    });
  };

  batchDelete = rows => {
    this.deleteData(rows); //批量删除
  };
  handleThisRowDelete = id => {
    const { dispatch } = this.props;
    return dispatch({
      type: 'scene/delete',
      payload: { sceneId: id },
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
          this.pageList();
          this.setState({ selectedRows: [] });
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      }, //callback
    });
  };

  componentDidMount() {
    this.props.queryList();
  }

  //复选框选择
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  // 分页查询列表
  pageList(pageSize = 10, pageNum = 0) {
    const values = {
      ...this.state.formValues,
      pageSize: this.state.pagination ? this.state.pagination.pageSize : pageSize,
      pageNum: this.state.pagination ? this.state.pagination.current - 1 : pageNum,
    };
    this.props.queryList(values);
  }

  handleStandardTableChange(pagination) {
    this.setState({ pagination }, () => this.pageList());
  }

  //查询
  handleSearch = e => {
    e.preventDefault();
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };
      this.setState(
        {
          formValues: values,
          pagination: '',
        },
        () => this.pageList()
      );
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  }; //重置
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="场景名称">
              {getFieldDecorator('sceneName')(<Input placeholder="" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  // 新增弹框的显示和隐藏
  handleModalVisible = (flag, text) => {
    this.setState({
      modalVisible: !!flag,
      text: text,
    });
  };

  // 更新接口
  updateFn = (fields, text) => {
    const { dispatch } = this.props;
    const params = {
      sceneId: text.sceneId,
      sceneCode:fields.sceneCode,
      sceneName:fields.sceneName,
      minLength:fields.minLength,
      maxLength:fields.maxLength,
      regularExpression:fields.regularExpression,     
      ifSearch:fields.ifSearch,
      ifUpdateKey:fields.ifSearch == 1?0:fields.ifUpdateKey,
      remark:fields.remark,      
    };    
    dispatch({
      type: 'scene/update',
      payload: params,
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
          // form.resetFields();
          this.handleModalVisible();
          this.pageList();
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
  };

  // 增加接口
  addDataFn = fields => {
    const { dispatch } = this.props;   
    const params = {
      sceneCode:fields.sceneCode,
      sceneName:fields.sceneName,
      minLength:fields.minLength,
      maxLength:fields.maxLength,
      regularExpression:fields.regularExpression,     
      ifSearch:fields.ifSearch,
      ifUpdateKey:fields.ifSearch == 1?0:fields.ifUpdateKey,
      remark:fields.remark,   
    };
    dispatch({
      type: 'scene/add',
      payload: params,
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
          this.pageList();
          // form.resetFields();
          this.handleModalVisible();
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
  };

  // 查看详情
handleView = (flag,text) => {
  this.setState({
    viewModalVisible: !!flag,
    text,
  });
};


  render() {
    const {
      scene: { data },
      loading,
      loadingupdate,
      loadingadd,
    } = this.props;
    const { selectedRows, modalVisible, viewModalVisible, text, } = this.state;
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      addDataFn: this.addDataFn,
      updateFn: this.updateFn,
    };  
    
    const viewMethods = {
      handleView: this.handleView,
    };
    return (
      <PageHeaderWrapper title="密钥规则管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新增
              </Button>
              {selectedRows.length > 0 && (
                <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
              )}
            </div>
            <TableList
              size="middle"
              selectedRows={selectedRows}
              rowKey="sceneId"
              rowSelection={{
                selectedRowKeys: this.state.selectedRows,
                onChange: e => this.setState({ selectedRows: e }),
                getCheckboxProps: record => ({
                  disabled: record.ifBuiltin == 1,
                }),
              }}
              loading={loading}
              data={data}
              columns={this.columns}
              onChange={this.handleStandardTableChange.bind(this)}
            />
          </div>
          <CreateForm
            {...parentMethods}
            modalVisible={modalVisible}
            text={text}
            loadingupdate={loadingupdate}
            loadingadd={loadingadd}
          />   
           {viewModalVisible?(
          <ViewScene {...viewMethods} viewModalVisible={viewModalVisible} text={text} />
        ):null}     
        </Card>
      </PageHeaderWrapper>
    );
  }
}

//查看详情弹窗
class ViewScene extends PureComponent {
  render() {
    const { viewModalVisible, handleView,text } = this.props;
    return (
      <Modal
        destroyOnClose
        width={800}
        title="查看场景"
        visible={viewModalVisible}
        onCancel={() => handleView(false)}
        footer={[
          <Button key="back" type="primary" onClick={() => handleView()}>返回</Button>
        ]}   
        className={styles.viewMore}     
      >
    <Row>
        <Col md={12}>
            <FormItem {...viewLayout} label="场景编码">
              {text.sceneCode}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...viewLayout} label="场景名称">
              {text.sceneName}
            </FormItem>
          </Col>  
          <Col md={12}>
            <FormItem {...viewLayout} label="敏感数据长度">
              {text.minLength} ~ {text.maxLength}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...viewLayout} label="模糊搜索">
              {text.ifSearch ==1?'支持':'不支持'}
            </FormItem>
          </Col>  
         
          <Col md={12}>
            <FormItem {...viewLayout} label="更换密钥">
              {text.ifUpdateKey ==1?'支持':'不支持'}
            </FormItem>
          </Col>  
          
          <Col md={12}>
            <FormItem {...viewLayout} label="是否内置">
              {text.ifBuiltin ==1?'是':'否'}
            </FormItem>
          </Col>  
          <Col md={24}>
            <FormItem labelCol={{span:3}} wrapperCol={{span:21}} label="正则表达式">
              {text.regularExpression}
            </FormItem>
          </Col>  
          <Col md={24}>
            <FormItem labelCol={{span:3}} wrapperCol={{span:21}} label="备注">
              {text.remark}
            </FormItem>
          </Col>  
    </Row>
      </Modal>
    );
  }
}


export default scene;
